/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.core.image.web.servlet.TextImageServlet
   Module Description   :

   Date Created      : 2010/3/18
   Original Author   : jeff.ma
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.core.image.web.servlet;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.image.entity.TextImage;
import com.yaodian100.core.image.service.ImageService;

/**
 * @author jeff.ma
 * 
 */
public class TextImageServlet extends HttpServlet {
	/** serialVersionUID */
	private static final long serialVersionUID = 7961533095910563677L;

	public static final String SESSION_KEY = "_yd100_checkimg";

	private ImageService imageService;

	/** default constructor */
	public TextImageServlet() {
	}

	@Override
	public void init() throws ServletException {
		ServletContext servletContext = getServletContext();
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		this.imageService = (ImageService) wac.getBean("imageService");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);

			TextImage img = imageService.create(0, 0);
			request.getSession().setAttribute(SESSION_KEY, img.getText());

			OutputStream fos = response.getOutputStream();
			fos.write(img.getBody());
			fos.flush();
			fos.close();
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
}
